<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>AI 流式输出测试 (改进版)</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #question {
            width: 100%;
            padding: 10px;
            font-size: 16px;
        }
        #sendBtn {
            padding: 10px 20px;
            font-size: 16px;
            margin: 10px 0;
            cursor: pointer;
        }
        #response {
            border: 1px solid #ccc;
            padding: 10px;
            min-height: 200px;
            white-space: pre-wrap;
            background-color: #f9f9f9;
        }
        .loading {
            color: #666;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <h1>AI 流式输出测试 (改进版)</h1>
    <textarea id="question" rows="4" placeholder="请输入你的问题...">请写一首关于人工智能的诗</textarea>
    <br>
    <button id="sendBtn">发送</button>
    <div id="response" class="loading">等待响应...</div>

    <script>
        document.getElementById('sendBtn').addEventListener('click', function() {
            const question = document.getElementById('question').value;
            const responseElement = document.getElementById('response');
            
            if (!question.trim()) {
                alert('请输入问题');
                return;
            }
            
            // 清空之前的响应
            responseElement.textContent = 'AI: ';
            responseElement.classList.remove('loading');
            
            // 创建 XMLHttpRequest 连接以更好地控制编码
            const xhr = new XMLHttpRequest();
            const url = `/ai/stream/ask?content=${encodeURIComponent(question)}`;
            
            xhr.open('GET', url, true);
            xhr.setRequestHeader('Accept', 'text/event-stream');
            xhr.setRequestHeader('Cache-Control', 'no-cache');
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            
            // 用于跟踪已处理的内容
            let processedText = '';
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.LOADING || xhr.readyState === XMLHttpRequest.DONE) {
                    // 处理流式数据
                    const newText = xhr.responseText.substring(processedText.length);
                    if (newText) {
                        // 解析 SSE 格式数据
                        const lines = newText.split('\n');
                        lines.forEach(line => {
                            if (line.startsWith('data:')) {
                                const data = line.substring(5).trim(); // 移除 "data:" 前缀
                                if (data) {
                                    try {
                                        // 尝试解码可能的URL编码内容
                                        const decodedData = decodeURIComponent(data);
                                        responseElement.textContent += decodedData;
                                    } catch (e) {
                                        // 如果解码失败，直接使用原始数据
                                        responseElement.textContent += data;
                                    }
                                }
                            }
                        });
                        processedText = xhr.responseText;
                        // 滚动到底部
                        responseElement.scrollTop = responseElement.scrollHeight;
                    }
                }
                
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status !== 200) {
                        responseElement.textContent += '\n[连接错误: ' + xhr.status + ']';
                        responseElement.classList.add('error');
                    }
                }
            };
            
            // 处理错误
            xhr.onerror = function() {
                responseElement.textContent += '\n[网络错误]';
                responseElement.classList.add('error');
            };
            
            // 发送请求
            xhr.send();
        });
    </script>
</body>
</html>